# -*- coding: utf-8 -*-
# @Date   : 2019/11/8
# @File   : EC07_Later6MonsUpaidLoanBalToTaxMonthlyIncomePro_GZ.py
# @Author : zhaochen

'''eof
name:企业未来6个月未结清到期贷款余额比月均申报收入总额
code:EC07_Later6MonsUpaidLoanBalToTaxMonthlyIncomePro_GZ_2D
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D,TX_GZ_DSJ
type:常用指标
dataSourceType:
eof'''


import sys
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')


def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None

def Later6MonsUpaidLoanBalPre():
    data = EC_DSJ_2D['data']
    factor = []
    # 借贷账户信息   [1..1]
    EDA = getTable(data,"EDA",1)
    if EDA is None:
        return None
    elif EDA == [{}] or EDA == "":
        return 0
    else:
        # 借贷账户信息单元   [0..*]
        ED01 = getTable(EDA[0], "ED01", 0)
        if ED01 in null_type_list:
            return None
        elif ED01 ==[{}]:
            return 0
        else:
            for i in ED01:
                try:
                    # 基本信息段   [1..1]
                    ED01A = getTable(i, 'ED01A', 1)
                    # 还款信息段   [1..1]
                    ED01B = getTable(i, 'ED01B', 1)
                    if ED01A in null_type_list:
                        factor.append(None)
                    elif ED01A == [{}]:
                        factor.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        # 到期日期   [0..1]
                        ED01AR02 = ED01A[0].get('ED01AR02')
                        # 借贷账户类型 ED01AD02
                        ED01AD02 = ED01A[0].get('ED01AD02')
                        if ED01AD01 in null_type_list or formatDate(ED01AR02) in null_type_list or ED01AD02 in null_type_list:
                            factor.append(None)
                        else:
                            now = datetime.datetime.now()
                            six_months = datetime.timedelta(days = 6*30)
                            end_date = (now + six_months)
                            #1-未结清
                            if ED01AD01 == '1' and  formatDate(ED01AR02) > now and formatDate(ED01AR02) <= end_date and ED01AD02 != 'D2':
                                if ED01B in null_type_list:
                                    factor.append(None)
                                elif ED01B == [{}]:
                                    factor.append(0)
                                else:
                                    # 还款表现信息   [0..*]
                                    ED01BH = getTable(ED01B[0],'ED01BH',0)
                                    if ED01BH in null_type_list:
                                        factor.append(None)
                                    elif ED01BH == [{}]:
                                        factor.append(0)
                                    else:
                                        for i in ED01BH:
                                            # 余额   [1..1]
                                            ED01BJ01 = i.get('ED01BJ01')
                                            if isfloat(ED01BJ01):
                                                factor.append(float(ED01BJ01))
                                            else:
                                                factor.append(None)
                            else:
                                factor.append(0)
                except:
                    factor.append(None)
                    continue
            factor = filter(lambda x: x is not None, factor)
            if len(factor) == 0:
                factor = None
            else:
                factor = sum(factor)
            return factor


#1-月均申报收入总额计算
null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTableTX(table_Name):
    try:
        ic_data = TX_GZ_DSJ['data'].get(table_Name)
        if ic_data is None:
            return None
        else:
            return ic_data if isinstance(ic_data, list) and len(ic_data) > 0 else [{}]
    except:
        return None


# 纳税人类型
def TaxerType():
    try:
        syptSwdjxx = getTableTX('syptSwdjxx')
        if syptSwdjxx == [{}] or syptSwdjxx is None:
            return None
        else:
            NSRZG_DM = syptSwdjxx[0].get('NSRZG_DM')
            if NSRZG_DM in null_type_list:
                return None
            elif NSRZG_DM not in null_type_list and NSRZG_DM in ['201', '202', '203', '204', '205']:
                return NSRZG_DM
            else:
                return u'其他'
    except:
        return None

# 一般纳税人
def ybnsr():
    try:
        syptZzsybnsr = getTableTX('syptZzsybnsr')
        if syptZzsybnsr is None or syptZzsybnsr == [{}]:
            return None
        else:
            # 可能存在统一年月 存在多次数据需要 用dict去重
            revenue = {}
            flag = []
            for i in syptZzsybnsr:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCont = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # 按适用税率计税销售额(ASYSLJSDNSJCYBJSE)
                    if isfloat(i.get('ASYSLJSDNSJCYBJSE')):
                        a1 = float(i.get('ASYSLJSDNSJCYBJSE'))
                    else:
                        a1 = 0
                        noneCont += 1
                    # “按简易办法计税销售额(AJYZSBFZSHWXSE)”
                    if isfloat(i.get('AJYZSBFZSHWXSE')):
                        a2 = float(i.get('AJYZSBFZSHWXSE'))
                    else:
                        a2 = 0
                        noneCont += 1
                    # 免、抵、退办法出口销售额(MDTBFCKHWXSE)
                    if isfloat(i.get('MDTBFCKHWXSE')):
                        a3 = float(i.get('MDTBFCKHWXSE'))
                    else:
                        a3 = 0
                    # 免税销售额(MSHWJLWXSE)
                    if isfloat(i.get('MSHWJLWXSE')):
                        a4 = float(i.get('MSHWJLWXSE'))
                    else:
                        a4 = 0
                        noneCont += 1
                    if noneCont == 4:
                        flag.append(None)
                    else:
                        # 存入每个月的收入
                        revenue.update({ND + YF: a1 + a2 + a3 + a4})
            if revenue == {} or len(flag) == len(syptZzsybnsr):
                return None
            else:
                return float(sum(list(revenue.values()))) / float(len(revenue))
    except:
        return None

# 小规模纳税人
def xgm():
    try:
        syptZzsxgm = getTableTX('syptZzsXgm')
        if syptZzsxgm is None or syptZzsxgm == [{}]:
            return None
        else:
            revenue = {}
            flag = []
            for i in syptZzsxgm:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCount = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # “应征增值税货物及劳务不含税销售额(YZZZSHWJLWBHSXSEBNBQ)”
                    if isfloat(i.get('YZZZSHWJLWBHSXSEBNBQ')):
                        a1 = float(i.get('YZZZSHWJLWBHSXSEBNBQ'))
                    else:
                        a1 = 0
                        noneCount += 1
                    # “销售、出租不动产不含税销售额(XSCZBDCBHSXSE)”
                    if isfloat(i.get('XSCZBDCBHSXSE')):
                        a2 = float(i.get('XSCZBDCBHSXSE'))
                    else:
                        a2 = 0
                        noneCount += 1
                    # “销售使用过的应税固定资产不含税销售额(XSSYGDYSGDZCBHSXSEBNBQ)”
                    if isfloat(i.get('XSSYGDYSGDZCBHSXSEBNBQ')):
                        a3 = float(i.get('XSSYGDYSGDZCBHSXSEBNBQ'))
                    else:
                        a3 = 0
                        noneCount += 1
                    # “免税货物及劳务销售额(MSHWJLWXSEBNBQ)”
                    if isfloat(i.get('MSHWJLWXSEBNBQ')):
                        a4 = float(i.get('MSHWJLWXSEBNBQ'))
                    else:
                        a4 = 0
                        noneCount += 1
                    # 出口免税货物销售额(CKMSHWXSEBNBQ)
                    if isfloat(i.get('CKMSHWXSEBNBQ')):
                        a5 = float(i.get('CKMSHWXSEBNBQ'))
                    else:
                        a5 = 0
                        noneCount += 1
                    # 字段都有问题
                    if noneCount == 5:
                        flag.append(None)
                    else:
                        revenue.update({ND + YF: a1 + a2 + a3 + a4 + a5})
                else:
                    flag.append(None)
            if revenue == {} or len(flag) == len(syptZzsxgm):
                return None
            else:
                fenmu=((datetime.datetime.strptime(max(revenue), '%Y%m').year-datetime.datetime.strptime(min(revenue), '%Y%m').year)*12+(datetime.datetime.strptime(max(revenue), '%Y%m').month-datetime.datetime.strptime(min(revenue), '%Y%m').month)*1)+3
                return float(sum(list(revenue.values()))) / fenmu
    except:
        return None

# 月均申报收入总和
def MonthlyIncomeReportAmt():
    try:
        taxerType = TaxerType()
        # 一般纳税人
        if taxerType in ['201', '202', '203']:
            result = ybnsr()
            if result is not None:
                return round(result, 4)
            else:
                return None
        # 小规模
        elif taxerType in ['204', '205']:
            result = xgm()
            if result is not None:
                return round(result, 4)
            else:
                return None
        # 其他情况
        elif taxerType is None or taxerType == u'其他':
            syptZzsxgm = getTableTX('syptZzsXgm')
            syptZzsybnsr = getTableTX('syptZzsybnsr')
            # 二者均为空
            if (syptZzsybnsr is None or syptZzsybnsr == [{}]) and (syptZzsxgm is None or syptZzsxgm == [{}]):
                return None
            # 二者均不为空
            elif syptZzsxgm not in [None, [{}]] and syptZzsybnsr not in [None, [{}]]:
                # 取出小规模纳税人表 和 一般纳税人表中 缴税年度和月份进行比较
                ybnsr_list = []
                xgm_list = []

                for i in syptZzsxgm:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isfloat(d):
                        xgm_list.append(float(d))
                    else:
                        pass

                for i in syptZzsybnsr:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isfloat(d):
                        ybnsr_list.append(float(d))
                    else:
                        pass

                if ybnsr_list == [] and xgm_list == []:
                    return None
                elif ybnsr_list != [] and xgm_list != []:
                    if max(ybnsr_list) >= max(xgm_list):
                        result = ybnsr()
                        if result is not None:
                            return round(result, 4)
                        else:
                            return None
                    else:
                        result = xgm()
                        if result is not None:
                            return round(result, 4)
                        else:
                            return None
                elif ybnsr_list != [] and xgm_list == []:
                    result = ybnsr()
                    if result is not None:
                        return round(result, 4)
                    else:
                        return None
                elif ybnsr_list == [] and xgm_list != []:
                    result = xgm()
                    if result is not None:
                        return round(result, 4)
                    else:
                        return None
                else:
                    assert False
            # 一般纳税人表为空 小规模不为空 用小规模纳税表计算
            elif syptZzsybnsr in [None, [{}]] and syptZzsxgm not in [None, [{}]]:
                result = xgm()
                if result is not None:
                    return round(result, 4)
                else:
                    return None
            # 一般纳税人不为空 小规模为空 用一般纳税人表计算
            elif syptZzsybnsr not in [None, [{}]] and syptZzsxgm in [None, [{}]]:
                result = ybnsr()
                if result is not None:
                    return round(result, 4)
                else:
                    return None
        else:
            assert False
    except:
        return None

def EC07_Later6MonsUpaidLoanBalToTaxMonthlyIncomePro():
    Factor1= Later6MonsUpaidLoanBalPre()
    Factor2 = MonthlyIncomeReportAmt()
    if Factor1==0 and Factor2==0:
        return 0
    elif Factor1 is None or Factor2 is None:
        return u'缺失值'
    else:
        try:
            result = float(Factor1) / float(Factor2)
        except:
            return u"缺失值"
        return round(result, 4)


result = EC07_Later6MonsUpaidLoanBalToTaxMonthlyIncomePro()


